/*
 * Copyright 2020-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.naja.auth2server.config;

import com.naja.auth2server.security.FederatedIdentityConfigurer;
import com.naja.auth2server.security.LoginUserService;
import com.naja.auth2server.security.UserRepositoryOAuth2UserHandler;
import com.naja.auth2server.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Steve Riesenberg
 * @since 0.2.3
 */
@EnableWebSecurity(debug = true)
public class DefaultSecurityConfig {
	@Bean
	WebSecurityCustomizer webSecurityCustomizer() {
		return (web) -> web.ignoring().antMatchers( "/assets/**","/webjars/**","/favicon.ico","/error");
	}
    // @formatter:off
	@Bean
	public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http,UserService userService) throws Exception {
		FederatedIdentityConfigurer federatedIdentityConfigurer = new FederatedIdentityConfigurer()
			.oauth2UserHandler(new UserRepositoryOAuth2UserHandler(userService));
		http
			.authorizeRequests(authorizeRequests ->
							authorizeRequests
									.mvcMatchers( "/login").permitAll()
				.anyRequest().authenticated()
			)
			.formLogin(Customizer.withDefaults())
//			.csrf()
//			.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
/*			.ignoringAntMatchers("/manage/**")*/
//			.and()
				.logout(logout->{
					logout.logoutSuccessHandler(new LogoutSuccessHandler() {@Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException, ServletException {
						response.sendRedirect(request.getParameter("redirect_uri"));

    }});
				})
				.csrf().disable()
			.apply(federatedIdentityConfigurer);
		return http.build();
	}
	// @formatter:on
	@Bean
	public UserDetailsService userDetailsService() {
		return new LoginUserService();
	}

    @Bean
    public DaoAuthenticationProvider getDaoAuthenticationProvider(UserDetailsService userDetailsService) {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        return daoAuthenticationProvider;
    }

}
